<template>
  <basic-container>
    <avue-crud :option="option"
               v-model:search="search"
               v-model:page="page"
               v-model="form"
               :table-loading="loading"
               :data="data"
               :permission="permissionList"
               :before-open="beforeOpen"
               ref="crud"
               @row-update="rowUpdate"
               @row-save="rowSave"
               @row-del="rowDel"
               @search-change="searchChange"
               @search-reset="searchReset"
               @selection-change="selectionChange"
               @current-change="currentChange"
               @size-change="sizeChange"
               @sort-change="sortChange"
               @refresh-change="refreshChange"
               @on-load="onLoad">
      <template #menu-left>
        <el-button type="danger"
                   icon="el-icon-delete"
                   effect="dark"
                   v-if="permission.service_country_mapping_delete"
                   @click="handleDelete">删 除
        </el-button>
        <el-divider direction="vertical" />
        <el-button type="success"
                   icon="el-icon-refresh"
                   effect="dark"
                   v-if="permission.service_country_mapping_country_sync && serviceApiId"
                   :loading="loading"
                   @click="handleCountrySync">国家同步
        </el-button>
        <el-button color="#626aef"
                   icon="el-icon-filter"
                   effect="dark"
                   v-if="permission.service_country_mapping_no_match"
                   :loading="loading"
                   @click="handleNoMatch">查询未配对数据
        </el-button>
        <el-divider direction="vertical" v-if="serviceApiId" />
        <el-button type="success"
                   icon="el-icon-refresh"
                   effect="dark"
                   v-if="permission.service_country_mapping_operator_sync && serviceApiId"
                   :loading="loading"
                   @click="handleOperatorSync">运营商同步
        </el-button>
        <el-divider direction="vertical" v-if="serviceApiId" />
        <el-button type="success"
                   icon="el-icon-refresh"
                   effect="dark"
                   v-if="permission.service_country_mapping_price_sync && serviceApiId"
                   :loading="loading"
                   @click="handlePriceSync">价格同步
        </el-button>
      </template>
      <template #serviceApiId="{ row }">
        <el-tag>{{ row.$serviceApiId }}</el-tag>
      </template>
      <template #countryId="{ row }">
        <el-tag>{{ row.$countryId }}</el-tag>
      </template>
      <template #status="{ row }">
        <el-tag :type="type.enable_disable[row.status]" effect="dark">{{ row.$status }}</el-tag>
      </template>
    </avue-crud>
  </basic-container>
</template>

<script>
import { getList, getDetail, add, update, remove, countrySync, operatorSync, priceSync } from '@/api/sms/service-country-mapping';
import option from '@/option/sms/service-country-mapping';
import { mapGetters } from 'vuex';
import func from '@/utils/func';
import type from '@/const/tag/type';

export default {
  data() {
    return {
      form: {},
      query: {},
      sort: {},
      search: {},
      loading: true,
      page: {
        pageSize: 10,
        currentPage: 1,
        total: 0
      },
      selectionList: [],
      option: option,
      data: []
    };
  },
  props: {
    serviceApiId: String,
    serviceConfigId: String
  },
  computed: {
    type() {
      return type;
    },
    ...mapGetters(['permission']),
    permissionList() {
      return {
        addBtn: this.validData(this.permission.service_country_mapping_add, false),
        viewBtn: this.validData(this.permission.service_country_mapping_view, false),
        delBtn: this.validData(this.permission.service_country_mapping_delete, false),
        editBtn: this.validData(this.permission.service_country_mapping_edit, false)
      };
    },
    ids() {
      let ids = [];
      this.selectionList.forEach(ele => {
        ids.push(ele.id);
      });
      return ids.join(',');
    }
  },
  created() {
    this.sort.descs = 'update_time';
    let findObject = this.findObject(this.option.column, 'serviceApiId');
    if (this.serviceApiId) {
      findObject.disabled = true;
      findObject.search = false;
    } else {
      findObject.disabled = false;
      findObject.search = true;
    }
  },
  methods: {
    rowSave(row, done, loading) {
      add(row).then(() => {
        this.onLoad(this.page);
        this.$message({
          type: 'success',
          message: '操作成功!'
        });
        done();
      }, error => {
        loading();
        window.console.log(error);
      });
    },
    rowUpdate(row, index, done, loading) {
      update(row).then(() => {
        this.onLoad(this.page);
        this.$message({
          type: 'success',
          message: '操作成功!'
        });
        done();
      }, error => {
        loading();
        console.log(error);
      });
    },
    rowDel(row) {
      this.$confirm('确定将选择数据删除?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          return remove(row.id);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
        });
    },
    handleDelete() {
      if (this.selectionList.length === 0) {
        this.$message.warning('请选择至少一条数据');
        return;
      }
      this.$confirm('确定将选择数据删除?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          return remove(this.ids);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
          this.$refs.crud.toggleSelection();
        });
    },
    beforeOpen(done, type) {
      if (['edit', 'view'].includes(type)) {
        getDetail(this.form.id).then(res => {
          this.form = res.data.data;
        });
      } else {
        if (this.serviceApiId) {
          this.form.serviceApiId = this.serviceApiId;
        }
      }
      done();
    },
    searchReset() {
      this.query = {};
      this.onLoad(this.page);
    },
    searchChange(params, done) {
      this.query = params;
      this.page.currentPage = 1;
      this.onLoad(this.page, params);
      done();
    },
    selectionChange(list) {
      this.selectionList = list;
    },
    selectionClear() {
      this.selectionList = [];
      this.$refs.crud.toggleSelection();
    },
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
    },
    sortChange(val) {
      this.sort = {};
      if (func.notEmpty(val.order)) {
        if (val.order === 'ascending') {
          this.sort.ascs = func.cameCaseToLine(val.prop);
        } else {
          this.sort.descs = func.cameCaseToLine(val.prop);
        }
      }
      this.refreshChange();
    },
    refreshChange() {
      this.onLoad(this.page, this.query);
    },
    onLoad(page, params = {}) {
      this.loading = true;

      if (this.serviceApiId) {
        params.serviceApiId = this.serviceApiId;
      }

      const {
        serviceApiId,
        countryId,
        countryIdNull,
        mappingId,
        updateTime,
        status
      } = Object.assign(params, this.query);

      let values = {
        serviceApiId_equal: serviceApiId,
        countryId_equal: countryId,
        mappingId_equal: mappingId,
        countryId_null: countryIdNull,
        updateTime_datege: updateTime ? updateTime[0] : undefined,
        updateTime_datelt: updateTime ? updateTime[1] : undefined,
        status_equal: status
      };

      getList(page.currentPage, page.pageSize, this.sort, values).then(res => {
        const data = res.data.data;
        this.page.total = data.total;
        this.data = data.records;
        this.loading = false;
        this.selectionClear();
      });
    },
    handleCountrySync() {
      this.loading = true;
      countrySync(this.serviceApiId, this.serviceConfigId).then(res => {
        this.loading = false;
        this.$notify({
          title: '同步成功',
          message: res.data.data,
          type: 'success',
          duration: 30000
        });
        this.searchReset();
      }, error => {
        this.loading = false;
      });
    },
    handleNoMatch() {
      this.query.countryIdNull = true;
      this.onLoad(this.page);
    },
    handleOperatorSync() {
      this.loading = true;
      operatorSync(this.serviceApiId, this.serviceConfigId).then(res => {
        this.loading = false;
        this.$notify({
          title: '同步成功',
          message: res.data.data,
          type: 'success',
          duration: 30000
        });
        this.searchReset();
      }, error => {
        this.loading = false;
      });
    },
    handlePriceSync() {
      this.loading = true;
      priceSync(this.serviceApiId, this.serviceConfigId).then(res => {
        this.loading = false;
        this.$notify({
          title: '同步成功',
          message: res.data.data,
          type: 'success',
          duration: 30000
        });
        this.searchReset();
      }, error => {
        this.loading = false;
      });
    }
  }
};
</script>

<style>
</style>
